package com.sencorsta.ids.game.other3rd;

import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.core.configure.SysConfig;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.game.db.SettlementResult;
import com.sencorsta.ids.game.other3rd.sdk.KyEncrypt;
import com.sencorsta.ids.game.other3rd.sdk.PostData;
import com.sencorsta.utils.date.DateUtil;
import com.sencorsta.utils.net.HttpRequester;
import com.sencorsta.utils.net.HttpRespons;
import com.sencorsta.utils.string.StringUtil;
import io.netty.handler.codec.http.QueryStringDecoder;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.*;

public class KyService {


    private static final String AGENT = SysConfig.getInstance().get("kaiyuan.Agent");
    private static final String DESKEY = SysConfig.getInstance().get("kaiyuan.Deskey");
    private static final String MD5KEY = SysConfig.getInstance().get("kaiyuan.Md5key");
    private static final String URL = SysConfig.getInstance().get("kaiyuan.api.url");


    public static String Login() throws Exception {
        //https://%3Cserver%3E/channelHandle?agent=XX&timestamp=XX&param=XX&key=XX

        //s=0&account=111111&money=10
        //0&orderid=1000120170306143036
        //949111111&ip=127.0.0.1&
        //lineCode =text11&KindID=0
        System.out.println("DESKEY:" + DESKEY);


        Date now = new Date();
        String nowStr = DateUtil.format(now, "yyyyMMddHHmmssSSS");
        String account = "10007";
        JSONObject param = new JSONObject();
        param.put("s", 0 + "");
        param.put("account", account);
        param.put("money", changeF2Y(25000));
        param.put("orderid", AGENT + nowStr + account);
        param.put("ip", "47.103.39.17");
        param.put("lineCode", "master");
        param.put("KindID", 0 + "");

        String paramStr = KyEncrypt.AESEncrypt(JsonToParamFixed(param), DESKEY);
        String key = KyEncrypt.MD5(AGENT + nowStr + MD5KEY);

        JSONObject req = new JSONObject();
        req.put("agent", AGENT);
        req.put("timestamp", nowStr);
        req.put("param", paramStr);
        req.put("key", key);

//        HttpRequester requester = new HttpRequester();
//        requester.timeOutConnect=15000;
//        requester.timeOutRead=15000;
//
//        HttpRespons respons = requester.sendGet(URL, req);
//        System.out.println("respons code:"+respons.getCode());
//        System.out.println("respons Content:" + respons.getContent());
//        if (respons.getCode()==0){
//            JSONObject res=JSONObject.parseObject(respons.getContent());
//            JSONObject d=res.getJSONObject("d");
//            if (d.getIntValue("code")==0) {
//                String gameUrl = d.getString("url");
//                return gameUrl;
//            }
//        }

        String resStr = PostData.get(URL+"?"+JsonToParamFixed(req));
        if (StringUtil.isNotEmpty(resStr)) {
            JSONObject res = JSONObject.parseObject(resStr);
            JSONObject d = res.getJSONObject("d");
            if (d.getIntValue("code") == 0) {
                String gameUrl = d.getString("url");
                return gameUrl;
            }
        }
        return "error";
    }
    public static long changeY2F(String moneyIn) {
        double price=Double.parseDouble(moneyIn);
        DecimalFormat df = new DecimalFormat("#.00");
        price = Double.valueOf(df.format(price));
        long money = (long)(price * 100);
        return money;
    }

    public static void main(String[] args) {
        //System.out.println(changeY2F("66.66"));
        System.out.println(changeF2Y(2500));
    }

    /**
     * 分转元，转换为bigDecimal在toString
     * @return
     */
    public static String changeF2Y(long price) {
        return BigDecimal.valueOf(Long.valueOf(price)).divide(new BigDecimal(100)).toString();
    }

    public static String Login(String account,long money) throws Exception {
        System.out.println("DESKEY:" + DESKEY);

        Date now = new Date();
        String nowStr = DateUtil.format(now, "yyyyMMddHHmmssSSS");
        JSONObject param = new JSONObject();
        param.put("s", 0 + "");
        param.put("account", account);
        param.put("money", changeF2Y(money));
        param.put("orderid", AGENT + nowStr + account);
        param.put("ip", "47.103.39.17");
        param.put("lineCode", "master");
        param.put("KindID", 0 + "");

        String paramStr = KyEncrypt.AESEncrypt(JsonToParamFixed(param), DESKEY);
        String key = KyEncrypt.MD5(AGENT + nowStr + MD5KEY);

        JSONObject req = new JSONObject();
        req.put("agent", AGENT);
        req.put("timestamp", nowStr);
        req.put("param", paramStr);
        req.put("key", key);

        String resStr = PostData.get(URL+"?"+JsonToParamFixed(req));
        if (StringUtil.isNotEmpty(resStr)) {
            JSONObject res = JSONObject.parseObject(resStr);
            JSONObject d = res.getJSONObject("d");
            if (d.getIntValue("code") == 0) {
                SettlementResult.doKyResult(account,-money);
                String gameUrl = d.getString("url");
                return gameUrl;
            }
        }
        return "error";
    }


    public static long getBalance(String account) throws Exception {
        //String agent,String account,String des,String md5,String apiUrl
        JSONObject kyMoneyJ=JSONObject.parseObject(PostData.getBalance(AGENT,account,DESKEY,MD5KEY,URL));
        Out.info("kyMoneyJ:"+kyMoneyJ);
        JSONObject d = kyMoneyJ.getJSONObject("d");
        if (d.getIntValue("code") == 0) {
            long kyMoneyJLong = changeY2F(d.getString("money"));
            Out.info("kyMoneyJLong:"+kyMoneyJLong);
            return kyMoneyJLong;
        }
        return 0;
    }

    public static boolean xiafen(String account,long money) throws Exception {
        String moneyStr=changeF2Y(money);
        //String agent,String account,String money,String orderid,String des,String md5,String apiUrl
        Date now = new Date();
        String nowStr = DateUtil.format(now, "yyyyMMddHHmmssSSS");
        String orderid=AGENT + nowStr + account;
        JSONObject kyMoneyJ=JSONObject.parseObject(PostData.xiafen(AGENT,account,moneyStr,orderid,DESKEY,MD5KEY,URL));
        Out.info("xiafen:"+kyMoneyJ);
        JSONObject d = kyMoneyJ.getJSONObject("d");
        if (d.getIntValue("code") == 0) {
            SettlementResult.doKyResult(account,money);
            return true;
        }
        return false;
    }


    public static String JsonToParamFixed(JSONObject params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        StringBuilder prestr = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = (String) params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr.append(key).append("=").append(value);
            } else {
                prestr.append(key).append("=").append(value).append("&");
            }
        }
        return prestr.toString();
    }

    public static String JsonToParamSort(JSONObject params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        StringBuilder prestr = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = (String) params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr.append(key).append("=").append(value);
            } else {
                prestr.append(key).append("=").append(value).append("&");
            }
        }
        return prestr.toString();
    }

    private static String getResponseBodyAsString(InputStream in) {
        try {
            BufferedInputStream buf = new BufferedInputStream(in);
            byte[] buffer = new byte[1024];
            StringBuffer data = new StringBuffer();
            int readDataLen;
            while ((readDataLen = buf.read(buffer)) != -1) {
                data.append(new String(buffer, 0, readDataLen, "UTF-8"));
            }
            System.out.println("响应报文=" + data);
            return data.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean checkSign(String inKey,String timeStr) {
        String key = KyEncrypt.MD5(AGENT + timeStr + MD5KEY);
        return key.equals(inKey);
    }


    public static JSONObject decodeParam(String param) throws Exception {
        String paramStr = KyEncrypt.AESDecrypt(param, DESKEY,false);
        return paramToMap(paramStr);
    }

    public static JSONObject paramToMap(String paramStr) {
        String[] params = paramStr.split("&");
        JSONObject res=new JSONObject();
        for (int i = 0; i < params.length; i++) {
            String[] param = params[i].split("=");
            if (param.length >= 2) {
                String key = param[0];
                String value = param[1];
                for (int j = 2; j < param.length; j++) {
                    value += "=" + param[j];
                }
                res.put(key, value);
            }
        }
        return res;
    }
}
